package com.sctvcloud.renhe.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.ServerTime;
import com.sctvcloud.renhe.R;
import com.sctvcloud.renhe.beans.FLiveProgram;
import com.sctvcloud.renhe.beans.FProgram;
import com.sctvcloud.renhe.beans.TvLivingList;
import com.sctvcloud.renhe.http.AbsNetCallBack;
import com.sctvcloud.renhe.http.NetUtils;
import com.sctvcloud.renhe.ui.adapter.TvLivingAdapter;
import com.sctvcloud.renhe.ui.util.RBaseItemDecoration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/7/13 0013.
 * 未使用
 */
public class TvLivingFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener {
    private final int WHAT_REFRESH_TIME = 919;
    @BindView(R.id.tv_living_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView living_list;
    private TvLivingAdapter livingAdapter;
    private LinearLayoutManager manager;
    private boolean mIsLoading = false;
    private List<FProgram> currentPrograms;
    private Handler handler;

    private Comparator programSort = new Comparator<FProgram>() {
        @Override
        public int compare(FProgram o1, FProgram o2) {
            if (o1 != null && o2 != null) {
//                return DateUtils.getDataDate(o2,0).compareTo(DateUtils.getDataDate(o1,0));
                return DateUtils.getDataDate(o1, 0).compareTo(DateUtils.getDataDate(o2, 0));
            }
            return 0;
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg != null) {
                    handMsg(msg);
                }
            }
        };
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tv_living, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        if (handler != null) {
            handler.removeMessages(WHAT_REFRESH_TIME);
        }
        super.onDestroyView();
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        living_list.setItemAnimator(new DefaultItemAnimator());
        living_list.addItemDecoration(new RBaseItemDecoration(2));
        living_list.setLayoutManager(manager);

    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        if (isFirst) {
            refreshLayout.autoRefresh();
        }
        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        mIsLoading = true;
//        if (TextUtils.isEmpty(((TvFragment) getParentFragment()).getProgramBackUrl())) {
//            ((TvFragment) getParentFragment()).setLoadingState(true);
//        }
        getData();
    }

    private void handMsg(Message msg) {
        if (msg.what == WHAT_REFRESH_TIME) {
            handler.removeMessages(WHAT_REFRESH_TIME);
            refreshProgramTime();
        }
    }

    public void getData() {
        if (TextUtils.isEmpty(channelUrl)) {
//            channelUrl = ((TvFragment) getParentFragment()).getChannelUrl();
            if (TextUtils.isEmpty(channelUrl)) {
                toast(R.string.data_wrong);
                refreshLayout.refreshComplete();
                mIsLoading = false;
                return;
            }
        }
        NetUtils.getNetAdapter().getTvLivingList(getOwnerName(), channelUrl, new AbsNetCallBack<TvLivingList>
                (TvLivingList.class) {

            private List<FProgram> programList;

            private int currentPos = -1;

            @Override
            public void onSuc(TvLivingList tvLivingList) {
                if (tvLivingList == null || !ListUtils.isListValued(tvLivingList.getLiveProgrammeList())) {
                    onError(null, null);
                    return;
                }
                if (ListUtils.isListValued(programList)) {
                    initData(programList, currentPos);
                } else {
                    makeToast(R.string.no_program_data);
                }


            }

            @Override
            public TvLivingList doInBackground(TvLivingList tvLivingList) {
                if (tvLivingList != null && ListUtils.isListValued(tvLivingList.getLiveProgrammeList())) {
                    programList = getCurrentDayProgramList(tvLivingList.getLiveProgrammeList());
                    if (ListUtils.isListValued(programList)) {
                        try {
                            Collections.sort(programList, programSort);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    currentPos = getCurrentProgramPos(programList);
                    if (ListUtils.isListValued(programList) && currentPos >= 0 && currentPos < programList.size() - 1) {
                        resetRemind(programList.get(currentPos + 1));
                    }
                }
                return super.doInBackground(tvLivingList);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
            }

            @Override
            public void onEnd() {
                onNetFinish();
            }
        });
    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        refreshLayout.refreshComplete();
    }

    /**
     * 获取当天的节目单,调用前需检查非空
     *
     * @return
     */
    private List<FProgram> getCurrentDayProgramList(List<FLiveProgram> datePrograms) {
        if (!ListUtils.isListValued(datePrograms)) {
            return null;
        }
        for (int i = 0; i < datePrograms.size(); i++) {
            FLiveProgram flp = datePrograms.get(i);
            if (flp != null) {
                if (DateUtils.isCurrentDate(DateUtils.getDataDate(flp))) {
                    return flp.getProgrammeList();
                }
            }
        }
        return null;
    }

    private int getCurrentProgramPos(List<FProgram> list) {
        long currentLong = DateUtils.getHourLong(ServerTime.getInstance(0).getServerRealTimeMilByEla());
        //JLog.e("aasa  " + DateUtils.getHoursLong("00:00:00") + "   " + Long.MIN_VALUE);
        if (ListUtils.isListValued(list)) {
            for (int i = list.size() - 1; i >= 0; i--) {
                FProgram fp = list.get(i);
                if (fp == null) {
                    list.remove(i);//此处不能将i加1
                    continue;
                }
                long time = fp.getStartTimeLongTemp();
                String s = fp.getStartTime();
                if (time <= DateUtils.OUTHOUR) {//中国的时区早晨8点为0,晚上0点为-2880000
                    time = DateUtils.getHoursLong(s);
                    fp.setStartTimeLongTemp(time);
                    JLog.e("long  " + time + "   " + s);
                }
                fp.setHasOutTime(false);
                if (currentLong > time && !TextUtils.isEmpty(s)) {
                    return i;
                }
            }
        }
        return -1;
    }

    private void refreshProgramTime() {
        if (livingAdapter != null) {
            int oldPos = livingAdapter.getSelectPos();
            int pos = getCurrentProgramPos(currentPrograms);
            if (oldPos != pos) {
                livingAdapter.setSelectPos(pos);
                if (oldPos >= 0) {
                    if (pos > oldPos) {
                        currentPrograms.get(oldPos).setHasOutTime(true);
                    }
                    livingAdapter.notifyItemChanged(oldPos);
                }
                if (pos >= 0) {
                    livingAdapter.notifyItemChanged(pos);
                }
            }
            if (pos >= 0 && pos < livingAdapter.getItemCount() - 1) {
                resetRemind(currentPrograms.get(pos + 1));
            }
        }
    }

    private void resetRemind(FProgram fp) {
        long time = fp.getStartTimeLongTemp();
        long cha = time - ServerTime.getInstance(0).getServerRealTimeMilByEla();
        if (cha > 0) {
            handler.sendEmptyMessageDelayed(WHAT_REFRESH_TIME, cha);
        }
    }

    private void convertData(TvLivingList tvLivingList) {
        List<FProgram> list = new ArrayList<>();
        String dateStr = DateUtils.formatDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd");

        //测试修改数据（将当前系统时间替换为接口字段时间，以便能显示数据）
//        dateStr = dateStr.replace(dateStr.substring(dateStr.lastIndexOf("-"), dateStr.length()), "-28");
        if (!ListUtils.isListValued(tvLivingList.getLiveProgrammeList())) {
            return;
        }

        for (int i = 0; i < tvLivingList.getLiveProgrammeList().size(); i++) {
            if (TextUtils.isEmpty(tvLivingList.getLiveProgrammeList().get(i).getLiveProgrammeDate())) {
                continue;
            }
            String dateS = tvLivingList.getLiveProgrammeList().get(i).getLiveProgrammeDate();
            if (!TextUtils.isEmpty(dateS) && dateS.contains(dateStr) && tvLivingList.getLiveProgrammeList().get
                    (i).getProgrammeList() != null) {
                list.addAll(tvLivingList.getLiveProgrammeList().get(i).getProgrammeList());
            }
        }

        if (list.size() == 0) {
            makeToast(R.string.no_program_data);
            return;
        }

//        initData(list);
    }

    private void initData(List<FProgram> fPrograms, final int currentPos) {
        JLog.e("fpros=" + fPrograms + "   pos=" + currentPos);
//        if (livingAdapter == null) {
        livingAdapter = new TvLivingAdapter(getActivity(), fPrograms).setItemInternalClick(livingOnItemClick);
        living_list.setAdapter(livingAdapter);
//        } else {
//            livingAdapter.setData(fPrograms);
//            livingAdapter.notifyDataSetChanged();
//        }
        livingAdapter.setSelectPos(currentPos);
        if (currentPos >= 0) {
            livingAdapter.notifyItemChanged(currentPos);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (manager != null) {
                        manager.scrollToPositionWithOffset(currentPos, 0);
                        manager.setStackFromEnd(true);
                    }
//                    living_list.smoothScrollToPosition(currentPos);
                }
            }, 500);

        }
        currentPrograms = fPrograms;
    }

    private OnItemInternalClick livingOnItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
//            FProgram fProgram = livingAdapter.getItem(position);
//            ((TvFragment) getParentFragment()).setPlayMedia(fProgram);
        }
    };

    private void makeToast(int strRes) {
//        if (((TvFragment) getParentFragment()).getIndexInViewPager() != ((HomeFragment) getParentFragment().getParentFragment())
//                .getCurrentSelectedIndex()) {
//            return;
//        }
        // toast(R.string.loading_no_data);
    }
}
